from sqlalchemy import Column, Integer, String, DateTime, Text, Boolean, JSON, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.database.connection import Base
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List

class Session(Base):
    """聊天会话模型"""
    
    __tablename__ = "chat_sessions"
    
    # 基础字段
    id = Column(Integer, primary_key=True, index=True, comment="会话ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True, comment="用户ID")
    session_title = Column(String(255), nullable=True, comment="会话标题")
    session_type = Column(String(50), default="general", comment="会话类型")
    status = Column(String(20), default="active", comment="会话状态")
    context_data = Column(JSON, nullable=True, comment="上下文数据")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关系
    messages = relationship("Message", back_populates="session", cascade="all, delete-orphan")
    
    def __repr__(self):
        """打印格式"""
        return f"<Session(id={self.id}, user_id={self.user_id}, title='{self.session_title}')>"
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "id": self.id,
            "user_id": self.user_id,
            "session_title": self.session_title,
            "session_type": self.session_type,
            "status": self.status,
            "context_data": self.context_data or {},
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
            "message_count": len(self.messages) if self.messages else 0
        }

class Message(Base):
    """聊天消息模型"""
    
    __tablename__ = "chat_messages"
    
    # 基础字段
    id = Column(Integer, primary_key=True, index=True, comment="消息ID")
    session_id = Column(Integer, ForeignKey("chat_sessions.id"), nullable=False, index=True, comment="会话ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True, comment="用户ID")
    role = Column(String(20), nullable=False, comment="角色(user/assistant)")
    content = Column(Text, nullable=False, comment="消息内容")
    message_type = Column(String(50), default="text", comment="消息类型")
    message_metadata = Column(JSON, nullable=True, comment="元数据")
    tokens_used = Column(Integer, nullable=True, comment="使用的token数")
    model_used = Column(String(100), nullable=True, comment="使用的模型")
    
    # 时间字段
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    
    # 关系
    session = relationship("Session", back_populates="messages")
    
    def __repr__(self):
        """打印格式"""
        return f"<Message(id={self.id}, session_id={self.session_id}, role='{self.role}')>"
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "id": self.id,
            "session_id": self.session_id,
            "user_id": self.user_id,
            "role": self.role,
            "content": self.content,
            "message_type": self.message_type,
            "message_metadata": self.message_metadata or {},
            "tokens_used": self.tokens_used,
            "model_used": self.model_used,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "timestamp": self.created_at.strftime("%Y-%m-%d %H:%M:%S") if self.created_at else None
        }